minmax_qual <- function(inpath, outpath,  para, maxlimit, minlimit, digit) {
  
## read data
  output <- sapply(seq(inpath), function(i) {
    df <- read.table(inpath[i], header = T, sep = ",", fill = T,
                   stringsAsFactors = F)
  
## Qualityflag - split
    qual <- as.character(df[["Qualityflag"]])
    #qual <- rep("0000000000000000", length(df[,1]))  
    qualleft <- substr(qual, 1, (digit - 1))
    qualact <- substr(qual, digit, (digit + 1))
    qualright <- substr(qual, (digit + 2), length(qual))
    
## Check physical limits, set Qualityflag
    qualact <- ifelse(df[[para]] < minlimit | df[[para]] > maxlimit, "r2", "r1")
    qualact <- ifelse(is.na(df[[para]]), "r3", qualact)
    qual <- paste(qualleft, qualact, qualright, sep = "")
    #print(qual)
    df["Qualityflag"] <- qual
    
## output
    write.table(df, outpath[i], col.names = T, row.names = F, sep = ",")
  })
}